<template>
  <div class="MenuTree-container">
    <a-spin :spinning="loading">
      <!-- <div class="searchWrapper">
        <a-input-search placeholder="请搜索" @change="handleChange" />
      </div> -->
      <div class="content" v-if="dataSource.length">
        <a-tree
          v-if="!loading"
          :tree-data="dataSource"
          :replaceFields="replaceFields"
          :expanded-keys.sync="expandedKeys"
          :loadData="loadTreeData"
          @select="handleSelect"
        >
          <template :slot="replaceFields.title" slot-scope="scopes">
            <span v-if="scopes[replaceFields.title].indexOf(searchValue) > -1">
              {{ scopes[replaceFields.title].substr(0, scopes[replaceFields.title].indexOf(searchValue)) }}
              <span style="color: #f50">{{ searchValue }}</span>
              {{
                scopes[replaceFields.title].substr(
                  scopes[replaceFields.title].indexOf(searchValue) + searchValue.length
                )
              }}
            </span>
            <span v-else>{{ scopes[replaceFields.title] }}</span>
          </template>
        </a-tree>
      </div>
      <a-empty description="暂无数据" v-else />
    </a-spin>
  </div>
</template>

<script>
import { Empty } from 'ant-design-vue'
import { clientId } from '@/config'
import { getPointDomains } from '@/api/system/system.js'
import { getSystemInfos, getResourceList } from '@/api/system/menuAndAuth.js'
export default {
  name: 'MenuTree',
  components: {
    AEmpty: Empty,
  },
  data() {
    return {
      searchValue: '',
      expandedKeys: [],
      selectedKeys: [],
      loading: false,
      dataSource: [],
      flatDataList: [],
      replaceFields: {
        title: 'name',
        key: 'id',
      },
    }
  },
  created() {
    this.getPointDomainsReq()
  },
  methods: {
    handleSelect(selectedKeys, { selected, node }) {
      const newKeys = selectedKeys.filter(item => !this.expandedKeys.includes(item))
      this.expandedKeys = this.expandedKeys.concat(newKeys)
      this.selectedKeys = selectedKeys
      this.$emit('selectNode', { ...node.dataRef, selected })
    },
    loadTreeData(treeNode) {
      const targetData = treeNode.dataRef
      return new Promise((resolve) => {
        if (targetData.children) {
          resolve()
          return
        }
        const fn = targetData.isDomain ? this.getSystemInfosReq : this.getResourceListReq
        fn(targetData[this.replaceFields.key], (response) => {
          if (!response) {
            resolve()
          } else {
            targetData.children = response.map((item) => {
              return {
                [this.replaceFields.title]: item.name,
                [this.replaceFields.key]: item.id,
                pid: targetData[this.replaceFields.key],
                domainId: item.domainId || item.singlePointDomainId, // 处理系统信息接口的情况
                systemId: item.singlePointDomainId ? item.id : item.systemId, // 处理系统信息接口的情况
                code: item.code
              }
            })
            this.dataSource = [...this.dataSource]
            resolve()
          }
        })
      })
    },
    /**
     * 获取资源列表
     * @param {String} parentId 资源列表的父级ID，即当前选中节点的ID
     */
    async getResourceListReq(parentId, callback) {
      try {
        const params = {
          parentId,
        }
        const res = await getResourceList(params)
        callback && callback(res.data)
      } catch {
        callback && callback(false)
      }
    },
    /**
     * 获取系统信息
     * @param {String} id 单点域ID
     */
    async getSystemInfosReq(id, callback) {
      try {
        const params = {
          singlePointDomainId: id,
        }
        const res = await getSystemInfos(params)
        callback && callback(res.data)
      } catch {
        callback && callback(false)
      }
    },
    async getPointDomainsReq() {
      if (this.loading) return
      this.loading = true
      try {
        const res = await getPointDomains()
        this.dataSource = res.data.map((item) => {
          return {
            [this.replaceFields.title]: item.name,
            [this.replaceFields.key]: item.id,
            pid: null,
            isDomain: true,
          }
        })
      } catch {
      } finally {
        this.loading = false
      }
    },
    // 刷新子节点
    reloadChildren(){
      if(!this.dataSource || !this.dataSource.length) return
      let node = this.findSelected(this.selectedKeys[0], this.dataSource)
      if(node.children) delete node.children
      this.loadTreeData({ dataRef: node })
    },
    findSelected(key, list){
      let node
      const dfs = data => {
        data.forEach(item => {
          if(item[this.replaceFields.key] === key){
            node = item
          }else if(item.children && !!item.children.length){
            dfs(item.children)
          }
        })
      }
      dfs(list)
      return node
    },
    // 搜索值变动
    handleChange(e) {
      const value = e.target.value
      this.searchValue = value
      const targetKeys = []
      // 获取包含查询结果节点的ID及其父级ID
      const expandedKeys = this.flatDataList
        .filter((item) => {
          if (item[this.replaceFields.title].indexOf(value) > -1 && value !== '') {
            targetKeys.push(item[this.replaceFields.key])
            return true
          }
          return false
        })
        .map((item) => item.pid)
      // 根据查询结果得到的id集合，更新节点的显示及隐藏
      const allKeys = expandedKeys.concat(targetKeys)
      const depFn = (list) => {
        list &&
          list.forEach((item) => {
            if (allKeys.includes(item.id) || value === '') {
              item.style.display = 'block'
            } else {
              item.style.display = 'none'
            }
            depFn(item.children)
          })
      }
      depFn(this.dataSource)
      this.expandedKeys = expandedKeys
    },
  },
}
</script>

<style lang="less" scoped>
.MenuTree-container {
  // min-height: 75vh;
  position: relative;
  .content {
    // height: 75vh;
    overflow: auto;
    scrollbar-width: thin;
    scrollbar-color: #ccc transparent;
    scrollbar-track-color: #fff;
    -ms-scrollbar-track-color: transparent;
    &::-webkit-scrollbar {
      background: #fff;
      width: 8px;
      height: 8px;
    }
    &::-webkit-scrollbar-thumb {
      /*滚动条里面小方块*/
      width: 8px;
      border-radius: 8px;
      border: 1px #fff solid;
      background: #ccc;
    }
  }
}
</style>